<template>
  <el-dialog
    v-model="dialogVisible"
    :title="pwsType === 1 ? '修改密码' : '账户密码已过期，请修改后再使用'"
    width="560px"
    draggable
  >
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="env.VITE_RELEASE_NAME === 'fendi' ? rules1 : rules2" label-width="100px">
      <el-form-item label="当前密码" prop="oldPsw">
        <el-input v-model="ruleForm.oldPsw" type="password" show-password />
      </el-form-item>
      <el-form-item label="新密码" prop="newPsw">
        <el-input v-model="ruleForm.newPsw" type="password" show-password />
      </el-form-item>
      <el-form-item label="确认新密码" prop="confirm">
        <el-input v-model="ruleForm.confirm" type="password" show-password />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="resetForm(ruleFormRef)">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
// import { checkPhoneNumber } from "@/utils/eleValidate";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { editLoginUserPassWord } from "@/api/modules/user";
import md5 from "js-md5";

const env = ref(import.meta.env);
const dialogVisible = ref(false);
// 密码校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("密码不能为空"));
  } else {
    const finalCheckPwd =
      /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,16}$/;

    // 校验密码
    const checkPwd: boolean = finalCheckPwd.test(ruleForm.newPsw);

    if (!checkPwd) {
      callback(new Error("密码必须不少于8位, 包含大小写、字母、字符至少三种"));
    } else {
      callback();
      // 注意，这个空的callback非常重要，没有它作为结束，整个校验会出问题
    }
  }
};
interface formData {
  userId: string | number;
  oldPsw: string;
  newPsw: string;
  confirm: string;
}
const ruleForm = reactive<formData>({
  userId: "",
  oldPsw: "",
  newPsw: "",
  confirm: ""
});
const emits = defineEmits(["logout"]);
const openDialog = () => {
  dialogVisible.value = true;
};
// 自定义验证
const equalToPassword = (rule: any, value: any, callback: any) => {
  if (ruleForm.newPsw !== value) {
    callback(new Error("两次输入的密码不一致"));
  } else {
    callback();
  }
};

const pwsType = ref(1);
// 接收父组件传过来的参数
const acceptParams = (params: formData) => {
  pwsType.value = params.row.type;
  if (params.row.type === 2) {
    ruleForm.userId = params.row.userId;
  }
  dialogVisible.value = true;
};

const rules1 = reactive<FormRules>({
  oldPsw: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPsw: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { required: true, trigger: "blur", validator: validatePass }
  ],
  confirm: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { required: true, validator: equalToPassword, trigger: "blur" } // 添加自定义验证器
  ]
});
const rules2 = reactive<FormRules>({
  oldPsw: [{ required: true, message: "请输入当前密码", trigger: "blur" }],
  newPsw: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirm: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { required: true, validator: equalToPassword, trigger: "blur" } // 添加自定义验证器
  ]
});

const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value.validate(async valid => {
    if (!valid) return;
    try {
      await editLoginUserPassWord({
        userId: ruleForm.userId || "",
        oldPsw: md5(ruleForm.oldPsw),
        newPsw: md5(ruleForm.newPsw)
      }).then(() => {
        ElMessage({
          message: "已修改密码，请重新登录!",
          grouping: true,
          type: "success"
        });
        dialogVisible.value = false;
        emits("logout", true);
      });
    } catch {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
  dialogVisible.value = false;
};

defineExpose({ openDialog, acceptParams });
</script>
